using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using PetShop.Web.Entities;
using PetShop.Web.WebComponents;

namespace PetShop.Web
{
    public partial class ShoppingCart : Page
    {
        private CartInfo myCart;


        protected decimal Total
        {
            get { return (decimal) ViewState["Total"]; }
        }

        protected override void OnLoad(EventArgs e)
        {
            myCart = (CartInfo) HttpContext.Current.Session["CART_KEY"];

            if (myCart == null)
            {
                myCart = new CartInfo();
            }

            if (!Page.IsPostBack)
            {
                string itemId = Request["itemId"];

                if (itemId != null)
                {
                    itemId = CleanString.InputText(itemId, 50);

                    ItemInfo itemInfo = null;

                    using (var cmd1 = new SqlCommand())
                    {
                        using (var conn1 = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                        {
                            cmd1.Connection = conn1;
                            cmd1.CommandText =
                                "SELECT Item.ItemId, Item.description, Item.InventoryQty, Item.ListPrice, Product.Name, Product.Descn FROM Item  INNER JOIN Product ON Item.ProductId = Product.ProductId WHERE Item.ItemId = @ItemId";
                            cmd1.CommandType = CommandType.Text;
                            var parm1 = new SqlParameter("@ItemId", SqlDbType.VarChar, 10);
                            parm1.Value = itemId;
                            cmd1.Parameters.Add(parm1);
                            conn1.Open();
                            using (SqlDataReader rdr = cmd1.ExecuteReader(CommandBehavior.CloseConnection))
                            {
                                rdr.Read();
                                itemInfo = new ItemInfo(rdr.GetString(0).Trim(), rdr.GetString(1), rdr.GetInt32(2),
                                                        rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5));
                            }
                        }
                    }


                    bool inStock1 = itemInfo.Quantity >= 1;
                    decimal price = itemInfo.Price;
                    string name = itemInfo.Name;
                    string dataId = itemInfo.Id;
                    var newItem = new CartItemInfo(dataId, name, inStock1, 1, price);
                    CartItemInfo data = newItem;

                    foreach (CartItemInfo cartItem in myCart.Items)
                    {
                        if (itemInfo.Id == cartItem.ItemId)
                        {
                            cartItem.Quantity++;
                            int qty = 0;


                            using (var cmd = new SqlCommand())
                            {
                                using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                                {
                                    cmd.Connection = conn;
                                    cmd.CommandText = "SELECT InventoryQty FROM Item WHERE ItemId = @ItemId";
                                    cmd.CommandType = CommandType.Text;
                                    var parm = new SqlParameter("@ItemId", SqlDbType.Char, 10);
                                    parm.Value = cartItem.ItemId;
                                    cmd.Parameters.Add(parm);
                                    conn.Open();
                                    object val = cmd.ExecuteScalar();
                                    if (val != null)
                                    {
                                        qty = Convert.ToInt32(val);
                                    }
                                }
                            }
                            int unitsInStock = qty;


                            int unitInStockprevision = unitsInStock - cartItem.Quantity;
                            bool inStock;
                            if (unitInStockprevision >= 0)
                            {
                                inStock = true;
                            }
                            else
                            {
                                inStock = false;
                            }
                            cartItem.InStock = inStock;
                        }
                    }

                    myCart.Add(data);

                    HttpContext.Current.Session["CART_KEY"] = myCart;
                }
            }

            var myAccount = (AccountInfo) HttpContext.Current.Session["ACCOUNT_KEY"];
            string favCategory = null;
            if (myAccount != null && myAccount.IsShowFavorites)
            {
                favCategory = myAccount.Category;
            }

            if (favCategory != null)
            {
                favorites.Visible = true;
                ViewState["Category"] = favCategory;
            }

            Refresh();
        }

        protected void CommandClicked(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "update")
            {
                TextBox txt;
                int qty;
                int index;

                for (int i = 0, j = cart.Items.Count; i < j; i++)
                {
                    txt = (TextBox) cart.Items[i].FindControl("txtQty");

                    try
                    {
                        qty = int.Parse(txt.Text);
                        index = cart.CurrentPageIndex*cart.PageSize + i;

                        if (qty <= 0)
                            myCart.RemoveAt(index);
                        else
                            myCart[index].Quantity = qty;
                    }
                    catch
                    {
                    }
                }
            }
            else
                myCart.Remove((string) e.CommandArgument);

            Refresh();

            int pageCount = (myCart.Count - 1)/cart.PageSize;
            cart.SetPage(Math.Min(cart.CurrentPageIndex, pageCount));
        }


        protected void CartPageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            cart.CurrentPageIndex = e.NewPageIndex;
            cart.DataSource = myCart.Items;
            cart.DataBind();
        }

        protected void FavoritesPageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            favorites.CurrentPageIndex = e.NewPageIndex;


            if (Cache[(string) ViewState["Category"]] != null)
            {
                favorites.DataSource = Cache[(string) ViewState["Category"]];
            }
            else
            {
                var productsByCategory = new List<ProductInfo>();

                using (var cmd = new SqlCommand())
                {
                    using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                    {
                        cmd.Connection = conn;
                        cmd.CommandText = "SELECT ProductId, Name FROM Product WHERE Category = @Category";
                        cmd.CommandType = CommandType.Text;
                        var parm = new SqlParameter("@Category", SqlDbType.Char, 10);
                        parm.Value = ViewState["Category"];
                        cmd.Parameters.Add(parm);
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (rdr.Read())
                            {
                                var product = new ProductInfo(rdr.GetString(0), rdr.GetString(1), null);
                                productsByCategory.Add(product);
                            }
                        }
                    }
                }

                Cache.Add((string) ViewState["Category"], productsByCategory, null, DateTime.Now.AddHours(12),
                          Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                favorites.DataSource = productsByCategory;
            }


            favorites.DataBind();
        }


        private void InitializeComponent()
        {
        }


        private void Refresh()
        {
            ViewState["Total"] = myCart.Total;
            link.Visible = myCart.Count > 0;
        }
    }
}